import { StyleSheet, Text, View, Image } from 'react-native';
import React, { useState, useEffect, useMemo } from 'react';
import Modal from 'react-native-modal';
import Icon from 'react-native-vector-icons/Ionicons';
import FastImage from '@d11/react-native-fast-image';
import { useTranslation } from 'react-i18next';
import LinearGradient from 'react-native-linear-gradient';
import { observer, deviceStore, userStore } from '~/store';
import { px2dp, scale } from '~/utils/px2dp';
import { yjhDevices } from '~/utils/deviceMenues';

interface Props {
    visible: boolean;
    onToggleVisible: Function;
    onModalHide?: any;
}
export default observer((props: Props) => {
    const { t } = useTranslation();
    const { visible, onToggleVisible, onModalHide } = props;
    const { userBindDeviceData, autoConnectDeviceSn } = userStore;
    const deviceInfo = useMemo(() => {
        const device = userBindDeviceData.find((item) => item.device_sn == autoConnectDeviceSn);
        return device;
    }, [userBindDeviceData, autoConnectDeviceSn]);
    const { searchDevices } = deviceStore.device;
    const [connectBleInfo, setConnectBleInfo] = useState<any>({});
    const isDevice = !!connectBleInfo; // 有数据就说明是匹配设备
    const [isConnect, setIsConnect] = useState(false);
    const connectDevice = (device) => {
        setIsConnect(true);
        if (yjhDevices.indexOf(device.device_code) !== -1) {
            deviceStore.connectBle(device, (res) => {
                if (res.status == 2) {
                    Toast.show({ content: t('ScanDeviceResult.t8') });
                    return;
                }
                Toast.show({ content: t('ConnectDeviceModal.t1') });
                onToggleVisible && onToggleVisible();
            });
        } else {
            deviceStore.connectBleUploadData(device, async (res) => {
                Toast.show({ content: t('ConnectDeviceModal.t1') });
                onToggleVisible && onToggleVisible();
            });
        }
    };
    useEffect(() => {
        if (!visible || !deviceInfo?.device_sn || !Array.isArray(searchDevices)) {
            setConnectBleInfo({});
            return;
        }
        const matched = searchDevices.find((device) => device?.device_sn === deviceInfo.device_sn && device?.id);
        if (matched && matched?.id) {
            setConnectBleInfo(matched ?? null);
            connectDevice(matched);
        }
        const timer = setTimeout(() => {
            Toast.show({ content: t('ConnectDeviceModal.t2') });
            onToggleVisible && onToggleVisible(); // 可选，超时后关闭弹窗
        }, 10000);
        return () => {
            clearTimeout(timer);
        };
    }, [visible, searchDevices, deviceInfo?.device_sn]);

    return (
        <Modal
            isVisible={visible}
            onModalHide={() => onModalHide && onModalHide()}
            presentationStyle="overFullScreen"
            statusBarTranslucent
            hasBackdrop>
            <LinearGradient
                pointerEvents="box-none"
                style={[styles.modalContainer]}
                colors={['#AFB8C8', '#3D4554']}
                start={{ x: 0, y: 0 }} // 顶部
                end={{ x: 0, y: 1 }}>
                <View style={[styles.row]}>
                    <View style={styles.imageBox}>
                        <Image
                            resizeMode="contain"
                            style={styles.logoImage}
                            source={{
                                uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/10/eecd820251009135831105.png',
                            }}
                        />
                    </View>
                    <View style={[styles.row, { position: 'relative' }]}>
                        <View style={styles.border}></View>
                        <View style={styles.line} />
                        <View style={styles.question}>
                            <Icon name={'alert-circle'} size={px2dp(70)} color={'#000'}></Icon>
                        </View>
                        <View style={styles.line} />
                        <View style={[styles.border, styles.border1]}></View>
                    </View>
                    <FastImage
                        style={styles.device_image}
                        source={{
                            uri: connectBleInfo?.device_image,
                            priority: FastImage.priority.normal,
                        }}
                        resizeMode={FastImage.resizeMode.contain}
                    />
                </View>
                <View style={styles.content}>
                    {isDevice ? (
                        <>
                            {isConnect ? (
                                <View style={[styles.row, { justifyContent: 'center' }]}>
                                    <Text style={styles.title}>{t('ConnectDeviceModal.t3')}</Text>
                                    <FastImage
                                        style={styles.loading}
                                        source={{
                                            uri: 'https://bjy-dev.oss-cn-shenzhen.aliyuncs.com/xcx/images/wait.gif',
                                            priority: FastImage.priority.normal,
                                        }}
                                    />
                                </View>
                            ) : (
                                <View style={[styles.row, { justifyContent: 'center' }]}>
                                    <Text style={styles.title}>{connectBleInfo?.device_sn}</Text>
                                </View>
                            )}
                        </>
                    ) : (
                        <View style={[styles.row, { justifyContent: 'center' }]}>
                            <Text style={styles.title}>{t('ConnectDeviceModal.t4')}</Text>
                            <FastImage
                                style={styles.loading}
                                source={{
                                    uri: 'https://bjy-dev.oss-cn-shenzhen.aliyuncs.com/xcx/images/wait.gif',
                                    priority: FastImage.priority.normal,
                                }}
                            />
                        </View>
                    )}

                    <View style={{ marginTop: px2dp(64) }}>
                        <Text style={styles.tips1}>1、{t('ConnectDeviceModal.t5')}</Text>
                        <Text style={styles.tips1}>2、{t('ConnectDeviceModal.t6')}</Text>
                    </View>
                    {/* {isDevice && (
                        <Pressable style={[styles.bt, styles.row]} onPress={connectDevice}>
                            <Text style={styles.bt_text}>
                                {isConnect ? t('ConnectDeviceModal.t7') : t('ConnectDeviceModal.t8')}
                            </Text>
                        </Pressable>
                    )} */}
                </View>
            </LinearGradient>
        </Modal>
    );
});

const styles = StyleSheet.create({
    modalContainer: {
        paddingVertical: px2dp(64),
        backgroundColor: '#fff',
        borderColor: 'rgba(255, 255, 255, 0.12)',
        borderRadius: px2dp(22),
    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    imageBox: {
        backgroundColor: '#000',
        width: px2dp(220),
        height: px2dp(400),
        borderTopRightRadius: px2dp(24),
        borderBottomRightRadius: px2dp(24),
    },
    logoImage: {
        width: px2dp(160),
        height: px2dp(240),
        marginBottom: px2dp(80),
        marginTop: px2dp(64),
    },
    device_image: {
        width: px2dp(220),
        height: px2dp(220),
    },
    border: {
        backgroundColor: '#E8CE35',
        width: px2dp(30),
        height: px2dp(30),
        borderRadius: px2dp(40),
    },
    border1: {
        position: 'absolute',
        bottom: 10,
        right: '-10%',
        zIndex: 9999999999,
    },
    line: {
        borderWidth: 2,
        borderColor: '#C2BA79',
        width: px2dp(80),
    },
    question: {
        width: px2dp(70),
        height: px2dp(70),
        backgroundColor: '#E8CE35',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: px2dp(40),
    },
    content: {
        flexGrow: 1,
        marginTop: px2dp(64),
    },
    title: {
        color: '#fff',
        textAlign: 'center',
        fontSize: scale(32),
        fontWeight: 'bold',
    },
    loading: {
        width: px2dp(60),
        height: px2dp(40),
    },
    tips1: {
        color: '#a4a4a4',
        marginHorizontal: px2dp(24),
        marginTop: px2dp(12),
        lineHeight: px2dp(40),
    },
    bt: {
        justifyContent: 'center',
        borderWidth: 1,
        borderColor: '#FFF',
        height: px2dp(96),
        marginTop: px2dp(64),
        borderRadius: px2dp(999),
        marginHorizontal: px2dp(120),
    },
    bt_text: {
        color: '#fff',
        fontSize: scale(32),
        fontWeight: 'bold',
    },
});
